package org.su.generalmvc.json;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

import java.util.HashMap;

/**
 * json对象处理辅助类，负责将java对象装换为json格式的字串，或将一个json转换为指定类型的java对象
 * @author yangchuan 2010-9-14 下午03:55:40
 *
 */
public class JsonHelper {
	private static ObjectMapper mapper = new ObjectMapper();


	private static JsonFactory jsonFactory = new JsonFactory(); 
	
	public static JsonFactory getJsonFactory(){
		return jsonFactory;
	}

	static{
		// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
		mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
	}

	/**
	 * 将对象转换成json字串
	 * @param obj 任意java对象
	 * @return 返回一个json字串
	 */
	public static String createJson(Object obj){
		try {
			return mapper.writeValueAsString(obj);
		} catch (Exception e) {
			throw new JsonCreateException("create json String fail。",e);
		}
	}
	
	/**
	 * 得到指定类型的对象
	 * @param <T>  合法的json格式的字符串
	 * @param clazz 目标转换类型
	 * @return 返回一个指定类型的java对象
	 */
	public static <T> T getObject(String src, Class<T> clazz){
		try {
			if(StringUtils.isBlank(src)){
				return null;
			}else{
				return mapper.readValue(src, clazz);
			}
		} catch (Exception e) {
			throw new JsonToObjException("can't convert this json to "+clazz + " type",e);
		}
	}

	/**
	 * 将json 转化为hashmap对象
	 * @param src json 字符串
	 * @return
	 */
	public static HashMap<String, Object>  getMapObject(String src){
		try {
			if(StringUtils.isBlank(src)){
				return null;
			}else{
				return (HashMap<String, Object>)mapper.readValue(src, HashMap.class);
			}
		} catch (Exception e) {
			throw new JsonToObjException("can't convert this json to hashmap type",e);
		}
	}
}
